package cn.wk.libs4a.utils;

import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import cn.wk.libs4a.R;
import cn.wk.libs4a.WKApplication;

import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SocializeClientListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMDataListener;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.TencentWBSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;

public class WKUmShareUtils {

	private Context ctx;

	// wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
	public String weixinAppID = "";
	public String weixinAppSecret = "";

	public String tencentAppID = "";
	public String tencentAppKEY = "";

	private String txt = "分享的txt";
	private String title = "分享的title";
	private String url = "http://www.umeng.com";

	public WKApplication app() {
		return (WKApplication) this.ctx.getApplicationContext();
	}

	/**
	 * 显示分享界面，image
	 */

	public void showShareView(String title, String txt, String url,
			UMImage image, Activity activity) {
		this.txt = txt;
		this.title = title;
		this.url = url;
		setQZoneSDK(activity);
		initUmShare(image);
	}

	// 友盟社会化分享
	public final UMSocialService mController = UMServiceFactory
			.getUMSocialService("com.umeng.share");

	public WKUmShareUtils(Context ctx, String weixinAppID,
			String weixinAppSecret, String tencentAppID, String tencentAppKEY) {
		this.ctx = ctx;

		this.weixinAppID = weixinAppID;
		this.weixinAppSecret = weixinAppSecret;
		this.tencentAppID = tencentAppID;
		this.tencentAppKEY = tencentAppKEY;
	}

	boolean isInitOK = false;

	public void setQZoneSDK(Activity activity) {
		QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(activity,
				tencentAppID, tencentAppKEY);
		qZoneSsoHandler.addToSocialSDK();
		UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(activity,
				tencentAppID, tencentAppKEY);
		qqSsoHandler.addToSocialSDK();

		mController.getConfig().setSsoHandler(qZoneSsoHandler);
		mController.getConfig().setSsoHandler(qqSsoHandler);
	}

	private void initSDK() {
		if (isInitOK)
			return;
		isInitOK = true;
		// mController.getConfig().setSsoHandler(qZoneSsoHandler);

		// 设置新浪SSO handler
		mController.getConfig().setSsoHandler(new SinaSsoHandler());
		// 设置腾讯微博SSO handler
		mController.getConfig().setSsoHandler(new TencentWBSsoHandler());
		// 添加微信平台
		UMWXHandler wxHandler = new UMWXHandler(ctx, weixinAppID,
				weixinAppSecret);
		wxHandler.addToSocialSDK();
		// 支持微信朋友圈
		UMWXHandler wxCircleHandler = new UMWXHandler(ctx, weixinAppID,
				weixinAppSecret);
		wxCircleHandler.setToCircle(true);
		wxCircleHandler.addToSocialSDK();
	}

	// 设置分享内容
	private void initContent(UMImage image) {
		mController.setShareContent(title + "\n" + txt + "\n" + url + "");

		// /*
		// * QQ AND QZone
		// */
		QQShareContent qqShareContent = new QQShareContent();
		// 设置分享文字
		qqShareContent.setShareContent(txt);
		// 设置分享title
		qqShareContent.setTitle(title);
		// 设置分享图片
		qqShareContent.setShareImage(image);
		// 设置点击分享内容的跳转链接
		qqShareContent.setTargetUrl(url);
		mController.setShareMedia(qqShareContent);

		QZoneShareContent qzone = new QZoneShareContent();
		// 设置分享文字
		qzone.setShareContent(txt);
		// 设置点击消息的跳转URL
		qzone.setTargetUrl(url);
		// 设置分享内容的标题
		qzone.setTitle(title);
		// 设置分享图片
		qzone.setShareImage(image);
		mController.setShareMedia(qzone);
		/*
		 * QQ AND QZone
		 */

		/*
		 * 微信分享／微信朋友圈分享
		 */
		// 设置微信好友分享内容
		// 设置分享图片
		// Drawable dra = ctx.getResources().getDrawable(R.drawable.logo);
		// BitmapDrawable bd = (BitmapDrawable) dra;
		// Bitmap bm = bd.getBitmap();
		// UMImage image = new UMImage(ctx, bm);

		WeiXinShareContent weixinContent = new WeiXinShareContent();
		// 设置分享文字
		weixinContent.setShareContent(txt);
		// 设置title
		weixinContent.setTitle(this.title);
		// 设置分享内容跳转URL
		if (url != null || !url.equals(""))
			weixinContent.setTargetUrl(url);
		if (image != null) {
			weixinContent.setShareImage(image);
		}
		mController.setShareMedia(weixinContent);

		// 设置微信朋友圈分享内容
		CircleShareContent circleMedia = new CircleShareContent();
		circleMedia.setShareContent(txt);
		// 设置朋友圈title
		circleMedia.setTitle(txt);
		circleMedia.setShareImage(image);
		if (url != null || !url.equals(""))
			circleMedia.setTargetUrl(url);
		mController.setShareMedia(circleMedia);

	}

	public void setWeixinContent() {

	}

	// 友盟社会化分享设置内容中可包含链接（人人网可单独设置链接）
	private void initUmShare(UMImage image) {
		initSDK();
		initContent(image);
		// 设置分享面板 微信分好友（需要打包出来）、朋友圈、新浪微博、腾讯微博
		mController.getConfig()
				.setPlatforms(SHARE_MEDIA.QZONE, SHARE_MEDIA.SINA,
						SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE);
		mController.getConfig()
				.setPlatformOrder(SHARE_MEDIA.QZONE, SHARE_MEDIA.SINA,
						SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE);
		mController.openShare(app().curAct, false);
	}

	// SSO授权回调
	public void activityResult(int requestCode, int resultCode, Intent data) {
		/** Umeng使用SSO授权必须添加如下代码 */
		UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(
				requestCode);
		if (ssoHandler != null) {
			ssoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}

	// 授权登录
	public void oAuthAction(final SHARE_MEDIA platform, final int id,
			final Handler handler, Context key) {
		mController.doOauthVerify(key, platform, new UMAuthListener() {

			@Override
			public void onStart(SHARE_MEDIA arg0) {
				// WKApplication.showToast("onStart");
			}

			@Override
			public void onError(SocializeException arg0, SHARE_MEDIA arg1) {
				WKApplication.showToast("授权出错");
			}

			@Override
			public void onComplete(Bundle value, SHARE_MEDIA arg1) {
				// Bundle[{access_key=2.00x3JfWC03t9ZId6dc0db97e0RY672,
				// expires_in=659174,
				// access_secret=2.00x3JfWC03t9ZId6dc0db97e0RY672,
				// uid=2314915883}]
				String uid = value.getString("uid");
				if (!TextUtils.isEmpty(uid)) {
					Message msg = handler.obtainMessage();
					msg.what = id;
					msg.obj = true;
					msg.sendToTarget();
				} else {
					WKApplication.showToast("授权失败");
				}
			}

			@Override
			public void onCancel(SHARE_MEDIA arg0) {
				WKApplication.showToast("您已经取消授权操作");
			}
		});
	}

	// 获取平台用户信息
	public void getPlatformInfo(final SHARE_MEDIA platform) {
		mController.getPlatformInfo(ctx, platform, new UMDataListener() {
			@Override
			public void onStart() {
			}

			@Override
			public void onComplete(int status, Map<String, Object> info) {
				if (status == 200 && info != null) {
					StringBuilder sb = new StringBuilder();
					Set<String> keys = info.keySet();
					for (String key : keys) {
						sb.append(key + "=" + info.get(key).toString() + "\r\n");
					}
					Log.d("UMengData", sb.toString());
					// uid=2314915883 favourites_count=0 location=山东 青岛
					// description=O_o...发小广告和转发小广告的就别关注我了，我不买，也更不会转发，谢谢.
					// verified=false friends_count=241 gender=1
					// screen_name=小二黑了个去 statuses_count=1549
					// followers_count=225
					// profile_image_url=http://tp4.sinaimg.cn/2314915883/180/5691477490/1
					// access_token=2.00x3JfWC03t9ZId6dc0db97e0RY672
					String plat = "";
					if (platform == SHARE_MEDIA.WEIXIN)
						WKAccessTokenKeeper.writeAccessTokenUM(
								WKAccessTokenKeeper.WEIXINPREFERENCES_NAME,
								ctx, info);
					else if (platform == SHARE_MEDIA.TENCENT)
						WKAccessTokenKeeper.writeAccessTokenUM(
								WKAccessTokenKeeper.QQPREFERENCES_NAME, ctx,
								info);
					else if (platform == SHARE_MEDIA.QZONE)
						WKAccessTokenKeeper.writeAccessTokenUM(
								WKAccessTokenKeeper.QZONEPREFERENCES_NAME, ctx,
								info);
					else if (platform == SHARE_MEDIA.SINA)
						WKAccessTokenKeeper.writeAccessTokenUM(
								WKAccessTokenKeeper.SINAPREFERENCES_NAME, ctx,
								info);
				} else {
					Log.d("UMengData", "发生错误：" + status);
				}
			}
		});
	}

	// 取消授权
	public void logoutOAuth(final SHARE_MEDIA platform, final int id,
			final Handler handlerLogout, final Context context) {
		new Thread() {
			public void run() {
				mController.deleteOauth(context, platform,
						new SocializeClientListener() {
							@Override
							public void onStart() {
							}

							@Override
							public void onComplete(int status,
									SocializeEntity arg1) {
								if (status == 200) {
									Message msg = handlerLogout.obtainMessage();
									msg.what = id;
									msg.obj = true;
									msg.sendToTarget();
								} else
									WKApplication.showToast("取消授权失败");
							}
						});
			}
		}.start();

	}
}
